from flask_restful import reqparse, Resource
from flask import session
from web.models import User
from web.utils.logs import logger

class UserLogin(Resource):
    """user login 类"""

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("username", type=str, required=True, location='json')
        self.parser.add_argument("password", type=str, required=True, location='json')
        self.parser.add_argument("rememberme", type=bool, location='json')

    def post(self):
        '''登录接口'''
        args = self.parser.parse_args()
        key_username = args.username
        key_password = args.password
        key_remember = args.rememberme
        
        # 检测用户是否存在
        user_query = User.query.filter(User.username == key_username).first()
        if not user_query:
            logger.info(f'用户登录失败，用户[{key_username}]不存在')
            return {'status_code': 201, 'msg': '用户名或密码错误'}

        # 密码校验
        if user_query.password == key_password:
            #session['status'] = True
            #session['username'] = key_username
            return {'status_code': 200}
        else:
            logger.info(f'用户登录失败，密码错误')
            return  {'status_code': 201, 'msg': '用户名或密码错误'}
        
